package com.qf.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.qf.constant.MessageConstant;
import com.qf.constant.RedisMessageConstant;
import com.qf.entity.Result;
import com.qf.pojo.Order;
import com.qf.service.OrderService;
import com.qf.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author zhouhao
 * @create 2021-12-24 19:35
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("submit")
    public Result submit(@RequestBody Map map){
        //获取前台提交过来的手机号
        String telephone = (String) map.get("telephone");
        //获取从redis缓存中存储的验证码
        String redisCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //获取页面上的验证码
        String validateCode  = (String) map.get("validateCode");
        //校验页面输入的验证码是否输入正确
        /*if (redisCode == null || !redisCode.equals(validateCode)){
            //验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }*/
        //验证码正确情况下去调用体检预约服务
        Result result = null;
        try {
            result =  orderService.addOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result.isFlag()){
            //预约成功  发送短信通知
            String orderDate = (String) map.get("orderDate");
            try {
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,orderDate);
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //根据id查询预约信息，包括套餐信息和会员信息
    @RequestMapping("findById")
    public Result findById(Integer id){
        try {
            Map<String,Object> map =  orderService.findById(id);
            //查询预约信息成功
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            //查询预约信息失败
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
